package client_updater

import org.mortbay.util.ajax.{ Continuation, ContinuationSupport }
import javax.servlet.http.{ HttpServlet, HttpServletRequest, HttpServletResponse }
import db.Client
import java.io.PrintWriter
import java.io.ObjectOutputStream
import java.io.OutputStream
import javax.servlet.ServletOutputStream

/**
 * extends HttpServlet. Holds every connected user in an endless suspend in order to be able to send him updates.
 */
class ForeverFrameServlet extends HttpServlet {

  var cc: Continuation = null

  /**
   * overrides HttpServlet.service.<br> when a client enters this servlet, 
   * it's suspended endlessly until a new update is available for him, then again. 
   */
  override def service(req: HttpServletRequest, resp: HttpServletResponse) {
    if (req.getRequestURI.contains("/login")) {
      cc = ContinuationSupport.getContinuation(req, null)
      val out = new PrintWriter(resp.getOutputStream)
      resp.setContentType("text/plain")
      resp.setStatus(HttpServletResponse.SC_OK)
      val client = new Client
      var UID = req.getParameter("UID").toLong
      client.setUserID(UID)
      var CID = req.getParameter("CID").toLong
      client.setClientID(CID)
      ClientsUpdater.addCont(cc, CID)
      println("connected user: uid="+UID+", cid="+CID)
      out.println("welcome!!")
      out.flush
      println("welcome")
      if(cc!=null)println("cc")
      while (true) {
        println("in loop")
        var result = cc.suspend(0)
        if(result==true){
          println("resuming: uid="+UID+", cid="+CID)
          out.println("New Update")
          out.flush
        }
        else println("timeout!!!")
      }
      out.println("bye")
      out.close
    }
  }
}
